package com.nuanshui.heatedloan.baseservice.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mongodb.BasicDBObject;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.form.StatisticsForm;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.Map;

@MqMessageHandler(RabbitMqQueue.RABBIT_MQ_STATISTICS)
public class StatisticsHandler implements RabbitmqMessageHandler {

	Logger log = org.slf4j.LoggerFactory.getLogger(StatisticsHandler.class);

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
		String body = new String(message.getBody(),"utf-8");
		LogUtil.info(log, "统计消息处理 start ");
		try {
			if("{}".equals(body)) {
			    channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);	
				return;
			}
			StatisticsForm form = JSON.parseObject(body,StatisticsForm.class);

			if(form.getOp()==StatisticsForm.OP_COVER && form.getUserAgent()!=null && SysStringUtils.isNotEmpty(form.getUserAgent().getUserId()))
			{
				Query query=Query.query(Criteria.where("userId").is(form.getUserAgent().getUserId()));
				mongoTemplate.remove(query,form.getEventId());
			}

			if(form.getType()==StatisticsForm.TYPE_SINGLE)
			{
				BasicDBObject basicDBObject = new BasicDBObject(JSON.parseObject(form.getParams()));
				saveObj(basicDBObject,form);
			}
			else if(form.getType()==StatisticsForm.TYPE_MULTIPLE)
			{
				JSONArray jsonList=JSON.parseArray(form.getParams());
				for (Object obj:jsonList) {
					BasicDBObject basicDBObject = new BasicDBObject((Map) obj);
					saveObj(basicDBObject,form);
				}
			}
			LogUtil.info(log, "统计消息处理  end ");
		} catch (Exception e) {
			log.error(body,e);
			e.printStackTrace();
		}	
	    channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
	}

	private void saveObj(BasicDBObject basicDBObject,StatisticsForm form)
	{
		basicDBObject.append("createdAt",new Date());

		String userId=basicDBObject.getString("userId");

		if(SysStringUtils.isEmpty(userId))
		{
			if(form.getUserAgent()!=null && SysStringUtils.isNotEmpty(form.getUserAgent().getUserId())) {
				userId = form.getUserAgent().getUserId();
				basicDBObject.append("userId", userId);
			}
		}

		if(!SysStringUtils.isEmpty(userId))
		{
			basicDBObject.append("userRawId", IdTypeHandler.decode(userId));
		} else
		{
			basicDBObject.append("userId", "");
			basicDBObject.append("userRawId", 0L);
		}

		mongoTemplate.save(basicDBObject,form.getEventId());
	}
}
